<?php

namespace App\Http\Controllers\Api;

use App\Models\Shop\Order;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Omnipay\Omnipay;
use Stripe\Stripe;

class StripeController extends Controller
{
    public function postNotify()
    {
        // Set your secret key: remember to change this to your live secret key in production
        // See your keys here: https://dashboard.stripe.com/account/apikeys
        Stripe::setApiKey("sk_live_WzGALSTOSwwVFKNSsHYTct9Q");

        // You can find your endpoint's secret in your webhook settings
        $endpoint_secret = "whsec_Do5wVGKMwqpwyT5WuRfwpUYgDTU5xmPH";

        $payload = @file_get_contents("php://input");
        $sig_header = $_SERVER["HTTP_STRIPE_SIGNATURE"];
        $event = null;
        file_put_contents("Stripe".time().".txt", var_export($payload, true));
        try {
            $event = \Stripe\Webhook::constructEvent(
                $payload, $sig_header, $endpoint_secret
            );
        } catch(\UnexpectedValueException $e) {
            // Invalid payload
            http_response_code(400); // PHP 5.4 or greater
            exit();
        } catch(\Stripe\Error\SignatureVerification $e) {
            // Invalid signature
            http_response_code(400); // PHP 5.4 or greater
            exit();
        }

        $payload = json_decode($payload);
        if($payload->type == 'charge.succeeded')
        {
            //获取订单ID
            $orderID = $payload->data->object->metadata->orderID;
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = Order::where('orderNumber', $orderID)->first();
            if (!$order)
            {
                http_response_code(400);
                exit();
            }
            // 检查订单是否已经更新过支付状态
            if ($order->payState == 1) { // 假设订单字段“支付时间”不为空代表已经支付
                http_response_code(200);
                exit(); // 已经支付成功了就不再更新了
            }
            // 用户是否支付成功
            $order->payState = 1; // 更新支付
            $order->save(); // 保存订单
        }

        http_response_code(200); // PHP 5.4 or greater
    }

}
